package com.hndzyu.yd.ui;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.R;
import com.hndzyu.yd.bean.Bean;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.GZIPOutputStream;

/**
 * Created by zz9527 on 2019/4/2.
 */
public class HBActivity extends Activity {
    private WebView web;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hb);
        ImmersionBar.with(this).statusBarColor(R.color.them).fitsSystemWindows(true).init();
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        web = findViewById(R.id.web);
        final ProgressBar pg1 = findViewById(R.id.progressBar);
        WebSettings webSettings = web.getSettings();
        webSettings.setDomStorageEnabled(true);
        // 启用js
        webSettings.setJavaScriptEnabled(true);
        //解决图片不显示
        webSettings.setBlockNetworkImage(false);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                if (newProgress == 100) {
                    //加载完网页进度条消失
                    pg1.setVisibility(View.GONE);
                } else {
                    //开始加载网页时显示进度条
                    pg1.setVisibility(View.VISIBLE);
                    //设置进度值
                    pg1.setProgress(newProgress);
                }
            }
        });
        web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        getPath();
    }

    private void getPath() {
        Gson gson = new Gson();
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = telephonyManager.getDeviceId();
        Bean bean = new Bean(deviceId);
        String json = gson.toJson(bean);
        byte[] bytes = compress(json);
        String md = Base64.encodeToString(bytes, Base64.NO_WRAP);
        String encode = URLEncoder.encode(md);
        int randomnum = (int) (Math.random() * 1000000);
        long currentTimeMillis = System.currentTimeMillis() / 1000;
        String sign = "appSecret=3XfyZ7dh7qCu6Lym3GnwA48hp23Q9qLNE6MPSfF" +
                "&md=" + md + "&nonce=" + randomnum + "&timestamp=" + currentTimeMillis;
        String signed = getSHA(sign);
        String path = "http://engine.tuicoco.com/index/activity?appKey=3FAqUyKfJ4ZF26G1onwLonpQNjvz&adslotId=273898" +
                "&md=" + encode + "&timestamp=" + currentTimeMillis + "&nonce=" + randomnum + "&signature=" + signed + "&deviceId=" + deviceId;
        Log.i("______", path);
        web.loadUrl(path);
    }


    /**
     * Gzip 压缩数据
     *
     * @param
     * @return
     */
    public static byte[] compress(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes());
            gzip.close();
        } catch (IOException e) {
            Log.e("gzip compress error.", e.getMessage());
        }
        return out.toByteArray();
    }

    public static String getSHA(String info) {
        byte[] digesta = null;
        try {
// 得到一个SHA-1的消息摘要
            MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
            alga.update(info.getBytes());
// 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
// 将摘要转为字符串
        String rs = byte2hex(digesta);
        return rs;
    }

    private static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (byte aB : b) {
            stmp = (Integer.toHexString(aB & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && web.canGoBack()) {
            web.goBack();//返回上个页面
            return true;
        }
        //退出H5界面
        return super.onKeyDown(keyCode, event);
    }
}
